<template>
  <div>
    <Dialog
      ref="Drawer"
      @close="close"
      :loading="loading"
      @handleSave="handleSave"
      :title="title"
      :disabled="disabled"
      :dialog="dialog"
    >
      <template #content>
        <el-form
          :model="ruleForm"
          :disabled="disabled"
          size="small"
          :rules="rules"
          ref="ruleForm"
          label-position="top"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="真实姓名"
                prop="realName"
              >
                <el-input
                  v-model="ruleForm.realName"
                  placeholder="请输入真实姓名"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="所属科室"
                prop="hospitalDepartId"
              >
                <!-- <el-select
              class="w100p"
              v-model="ruleForm.hospitalDepartId"
              placeholder="请选择所属科室"
            >
              <el-option
                v-for="item in departmentList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select> -->
                <Treeselect
                  class="w100p"
                  v-model="ruleForm.hospitalDepartId"
                  placeholder="请选择所属科室"
                  :options="departmentList"
                  :load-options="loadOptions"
                  :defaultOptions="true"
                  searchPromptText="请输入科室名称或者首字母拼音"
                  :async="true"
                  noResultsText="暂无数据"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="角色名称"
                prop="roleId"
              >
                <el-select
                  class="w100p"
                  v-model="ruleForm.roleId"
                  placeholder="请选择角色名称"
                >
                  <el-option
                    v-for="item in roleList"
                    :key="item.id"
                    :disabled="item.disabled"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                v-if="title == '新增人员'"
                label="手机号码"
                prop="mobile"
              >
                <el-input
                  v-model="ruleForm.mobile"
                  placeholder="请输入手机号码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="身份证号码"
                prop="idNumber"
              >
                <el-input
                  v-model="ruleForm.idNumber"
                  placeholder="请输入身份证号码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="工号"
                prop="jobNumber"
              >
                <el-input
                  v-model="ruleForm.jobNumber"
                  placeholder="请输入工号"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="常用邮箱"
                prop="email"
              >
                <el-input
                  v-model="ruleForm.email"
                  placeholder="请输入常用邮箱"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
      </template>
    </Dialog>
  </div>
</template>
<script>
import Dialog from "@/components/Dialog";
import * as department from "@/api/department";
import { IdentityCodeValid, treeDataTranslate } from "@/utils";
import { roleList } from "@/api/setting1.js";
import { hospitalDepartList } from "@/api/hospitalDepart.js";
import { ASYNC_SEARCH } from "@riophae/vue-treeselect";
export default {
  components: {
    Dialog,
  },
  data() {
    const validateUserPhone = (rule, value, callback) => {
      if (value && !/^1(3|4|5|6|7|8|9)\d{9}$/.test(value)) {
        callback(new Error("电话有误，请重填"));
      } else {
        callback();
      }
    };
    const validateUserEmail = (rule, value, callback) => {
      if (value && !/^\w+@[a-z0-9]+\.[a-z]{2,4}$/.test(value)) {
        callback(new Error("填写的邮箱格式错误,请重新填写!"));
      } else {
        callback();
      }
    };
    const validateCardId = (rule, value, callback) => {
      if (value && !IdentityCodeValid(value)) {
        callback(new Error("输入身份证格式错误请重新输入"));
      } else {
        callback();
      }
    };
    const validateRealName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入真实姓名"));
      } else if (
        value &&
        !/^[\u4E00-\u9FA5]{1,25}$|^[A-Za-z]{1,50}$/.test(value)
      ) {
        callback(new Error("真实姓名不超过50个英文字符或25个汉字"));
      } else {
        callback();
      }
    };
    const validateJobNumber = (rule, value, callback) => {
      if (value.length > 20) {
        callback(new Error("工号长度小于20位"));
      } else {
        callback();
      }
    };
    return {
      dialog: false, //弹框
      disabled:false,
      rules: {
        //form表单非空校验
        realName: [
          {
            required: true,
            validator: validateRealName,
            trigger: "blur",
          },
        ],
        jobNumber: [
          {
            validator: validateJobNumber,
            trigger: "blur",
          },
        ],
        hospitalDepartId: [
          {
            required: true,
            message: "请选择所属科室",
            trigger: "change",
          },
        ],
        roleId: [
          {
            required: true,
            message: "请选择所属角色",
            trigger: "change",
          },
        ],
        idNumber: [
          {
            validator: validateCardId,
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            validator: validateUserPhone,
            trigger: "blur",
          },
        ],
        email: [
          {
            validator: validateUserEmail,
            trigger: "blur",
          },
        ],
      },
      ruleForm: {
        //表单提交
        userStaffId: "", //用户id
        email: "", //常用邮箱
        hospitalDepartId: null, //所属科室
        idNumber: "", //身份证号码
        jobNumber: "", //工号
        mobile: "", //手机号码
        realName: "", //真实姓名
        roleId: "", //角色
      },
      formLabelWidth: "100px", //表单label宽度
      loading: false, //表单提交按钮
      passwordType: "password",
      title: "",
      departmentList: [], //科室列表
      roleList: [], //角色列表
    };
  },
  methods: {
    //弹框关闭
    close() {
      this.dialog = false;
    },
    async loadOptions({ action, searchQuery, callback }) {
      let _this = this;
      if (action === ASYNC_SEARCH) {
        let res = await hospitalDepartList({
          isPage: false,
          name: searchQuery,
        });
        if (res && res.success) {
          let departmentList = res.data.map((item) => {
            item.label = item.name;
            return item;
          });
          this.departmentList = treeDataTranslate(departmentList);
          callback(null, this.departmentList);
        }
      }
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    //获取角色列表
    handleGetRoleList() {
      roleList({ isPage: false, doublePlatformFlag: "1" }).then((res) => {
        if (res && res.success) {
          if (res.data) {
            this.roleList = res.data.map((item) => {
              item.disabled = item.isFreeze == 1 ? true : false;
              return item;
            });
          }
        }
      });
    },
    //获取科室列表
    handleHospitalDepartList() {
      hospitalDepartList({ isPage: false }).then((res) => {
        if (res && res.success) {
          let departmentList = res.data.map((item) => {
            item.label = item.name;
            return item;
          });
          this.departmentList = treeDataTranslate(departmentList);
        }
      });
    },
    //初始化弹框
    showModal(_type, _row) {
      this.dialog = true;
      //获取角色列表
      this.handleGetRoleList();
      this.handleHospitalDepartList();
      this.ruleForm.userStaffId = "";
      this.ruleForm.mobile = "";
      this.disabled = false
      this.$nextTick((_) => {
        this.$refs.ruleForm.resetFields();
        if (_type == "edit") {
          this.ruleForm = JSON.parse(JSON.stringify(_row));
          this.title = "编辑人员";
        } else if (_type == "view") {
          this.disabled = true
          this.ruleForm = JSON.parse(JSON.stringify(_row));
          this.title = "查看人员";
        } else {
          this.title = "新增人员";
        }
      });
    },
    //提交保存
    handleSave() {
      this.loading = true;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          department
            .sysUserStaffSave(this.ruleForm)
            .then((res) => {
              if (res && res.success) {
                this.loading = false;
                this.dialog = false;
                this.$emit("getDataList");
              } else {
                this.loading = false;
              }
            })
            .catch((e) => {
              this.loading = false;
            });
        } else {
          this.loading = false;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
$dark_gray: #889aa4;
.show-pwd {
  position: absolute;
  right: 10px;
  font-size: 16px;
  color: $dark_gray;
  cursor: pointer;
  user-select: none;
}
::v-deep .vue-treeselect__control {
  height: 32px;
  line-height: 32px;
}

::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  line-height: 32px;
}
</style>